package com.example.fill;

import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.SurfaceTexture;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.TextureView;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

public class StrLayoutTexture extends TextureView implements TextureView.SurfaceTextureListener {
    private Paint paint = new Paint();

    public StrLayoutTexture(@NonNull Context context) {
        super(context);
        setSurfaceTextureListener(this);
        setOpaque(false);//设置透明
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    public StrLayoutTexture(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setSurfaceTextureListener(this);
        setOpaque(false);//设置透明
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    public StrLayoutTexture(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public StrLayoutTexture(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
        int colorBg = ContextCompat.getColor(getContext(), R.color.md_theme_dark_onPrimary);
        int[] colors = {ColorUtils.toAlpha(colorBg, 0.01f), ColorUtils.toAlpha(colorBg, 0.25f), ColorUtils.toAlpha(colorBg, 0.01f)};
        float[] positions = {0, 0.5f, 1};
        LinearGradient linearGradient = new LinearGradient(0, 0, 0, height, colors, positions, Shader.TileMode.CLAMP);
        paint.setShader(linearGradient);
        startDraw();
    }

    @Override
    public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) {

    }

    @Override
    public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) {
        return false;
    }

    @Override
    public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {

    }

    private void startDraw() {
        Canvas canvas = lockCanvas();
        if (canvas != null){
            canvas.drawColor(Color.WHITE);
            canvas.drawRect(0,0,getWidth(),getHeight(),paint);
            unlockCanvasAndPost(canvas);
        }
    }
}
